package com.ellecity06.common.widgets

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import com.ellecity06.common.R
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

class CircularCustomizeView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    companion object {
        const val FILL = 0
        const val STROKE = 1
    }

    // 画笔
    private val mPaint: Paint

    // 圆环宽度
    private var mAnnulusWidth = 0

    // 圆环颜色
    private var mAnnulusColor = 0

    // 加载进度圆弧扫过的颜色
    private var mLoadColor = 0

    // 百分比文本颜色
    private var mTextColor = 0

    // 百分比文本大小
    private var mTextSize = 0

    // 进度
    private var mProgress = 0

    // 最大进度，默认100
    private val maxProgress = 100

    // 类型：0代表实心  1代表空心
    private var mProgressType = 1

    // 是否显示百分比文本
    private var mIsShowText = 0

    //是否显示百分比
    private var mIsPercentage = true

    //当不显示百分比时，数值的单位
    private var mTextContent: String = ""

    private val rect: Rect
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        // TODO:绘制圆环
        // 获取圆形坐标
        val centre = width / 2
        // 获取半径
        val radius = centre - mAnnulusWidth / 2
        // 取消锯齿
        mPaint.isAntiAlias = true
        // 设置画笔宽度
        mPaint.strokeWidth = mAnnulusWidth.toFloat()
        // 设置空心
        mPaint.style = Paint.Style.STROKE
        // 设置画笔颜色
        mPaint.color = mAnnulusColor
        //圆角
        mPaint.strokeCap = Paint.Cap.ROUND
        canvas.drawCircle(centre.toFloat(), centre.toFloat(), radius.toFloat(), mPaint)

        // TODO:画圆弧，进度
        // 设置进度颜色
        mPaint.color = mLoadColor
        mPaint.strokeWidth = mAnnulusWidth.toFloat()
        when (mProgressType) {
            STROKE -> {
                mPaint.style = Paint.Style.STROKE
                // 用于定义的圆弧的形状和大小的界限
                val ovalStroke = RectF(
                    (centre - radius).toFloat(), (centre - radius).toFloat(),
                    (centre + radius).toFloat(), (centre + radius).toFloat()
                )
                /**
                 * startAngle：从-90°开始，也就是钟表的12点钟位置。
                 * sweepAngle：圆弧扫过的角度
                 * useCenter：设置我们的圆弧在绘画的时候，是否经过圆形，当Paint.Style.STROKE时，true无效果
                 */
                canvas.drawArc(
                    ovalStroke,
                    -90f,
                    (mProgress * 360 / maxProgress).toFloat(),
                    false,
                    mPaint
                )
            }
            FILL -> {
                mPaint.style = Paint.Style.FILL
                // 用于定义的圆弧的形状和大小的界限
                val ovalFill = RectF(
                    (centre - radius - mAnnulusWidth / 2).toFloat(),
                    (centre - radius - mAnnulusWidth / 2).toFloat(),
                    (centre + radius + mAnnulusWidth / 2).toFloat(),
                    (centre + radius + mAnnulusWidth / 2).toFloat()
                )
                canvas.drawArc(
                    ovalFill,
                    -90f,
                    (mProgress * 360 / maxProgress).toFloat(),
                    true,
                    mPaint
                )
            }
        }

        // 如果不显示文本，直接return
        if (mIsShowText == 1) return
        // TODO：绘制文本
        // 计算圆弧进度获取文本内容
        var textContent = ""
        if (mIsPercentage) {
            val percentContext = (mProgress.toFloat() / maxProgress.toFloat() * 100f).toInt()
            textContent = "$percentContext%"
        } else {
            textContent = mTextContent
        }
        // 设置绘制文本画笔颜色
        mPaint.color = mTextColor
        // 设置绘制文本画笔风格
        mPaint.style = Paint.Style.FILL
        // 设置绘制文本画笔宽度，可添加自定义属性
        mPaint.strokeWidth = 3f
        // 测量文本宽度
        val measureTextWidth = mPaint.measureText(textContent)
        canvas.drawText(
            textContent,
            centre - measureTextWidth / 2,
            (centre + rect.height() / 2).toFloat(),
            mPaint
        )
    }

    /**
     * 根据外部进度传递更新View
     *
     * @param progress
     */
    fun setProgress(progress: Int) {
        mIsPercentage = true
        setProgress(progress, "")

    }

    /**
     * 根据外部进度传递更新View
     *
     * @param progress
     */
    fun setProgress(progress: Int, text: String) {
        mProgress = progress
        if (!mIsPercentage) {
            mTextContent = text
        }
        postInvalidate()

    }

    fun getmProgress(): Int {
        return mProgress
    }

    /**
     * 如果含有自定义属性，则重写带有三个参数的构造方法
     *
     * @param context
     * @param attrs
     * @param defStyleAttr
     */
    init {
        // 获取自定义属性
        val a = context.theme.obtainStyledAttributes(
            attrs,
            R.styleable.circularCustomizeView,
            defStyleAttr,
            0
        )
        val indexCount = a.indexCount
        for (i in 0 until indexCount) {
            val aIndex = a.getIndex(i)
            when (aIndex) {
                R.styleable.circularCustomizeView_annulusWidth -> mAnnulusWidth =
                    a.getDimensionPixelSize(
                        aIndex, TypedValue.applyDimension(
                            TypedValue.COMPLEX_UNIT_DIP, 10f,
                            resources.displayMetrics
                        ).toInt()
                    )
                R.styleable.circularCustomizeView_circularColor -> mAnnulusColor =
                    a.getColor(aIndex, Color.BLACK)
                R.styleable.circularCustomizeView_loadColor -> mLoadColor =
                    a.getColor(aIndex, Color.BLACK)
                R.styleable.circularCustomizeView_textColor -> mTextColor =
                    a.getColor(aIndex, Color.BLACK)
                R.styleable.circularCustomizeView_textSize -> mTextSize = a.getDimensionPixelSize(
                    aIndex, TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 15f,
                        resources.displayMetrics
                    ).toInt()
                )
                R.styleable.circularCustomizeView_progressType -> mProgressType =
                    a.getInt(aIndex, 1)
                R.styleable.circularCustomizeView_isShowText -> mIsShowText = a.getInt(aIndex, 1)
                R.styleable.circularCustomizeView_progress -> mProgress = a.getInt(aIndex, 10)
                R.styleable.circularCustomizeView_isPercentage -> mIsPercentage =
                    a.getBoolean(aIndex, true)
                R.styleable.circularCustomizeView_textContent -> mTextContent =
                    a.getString(aIndex) ?: ""
            }
        }
        a.recycle()
        mPaint = Paint()
        rect = Rect()
        // 设置画笔颜色
        mPaint.textSize = mTextSize.toFloat()
        // 返回在边界最小矩形，用户测量文本高度，因为文本高度根据字体大小固定
        mPaint.getTextBounds("%", 0, "%".length, rect)
    }


}